package com.bsg.upm.interceptor;

import java.io.PrintWriter;
import java.lang.reflect.Method;
import java.util.Arrays;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.http.HttpStatus;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import com.alibaba.fastjson.JSONObject;
import com.bsg.upm.annotation.Auth;
import com.bsg.upm.entity.UserEntity;
import com.bsg.upm.http.RespJsonFactory;

public class AuthInterceptor extends HandlerInterceptorAdapter {

	@Override
	public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler)
			throws Exception {
		response.setCharacterEncoding("UTF-8");
		response.setContentType("application/json; charset=utf-8");
		if (handler instanceof HandlerMethod) {
			String[] auths = null;
			Method m = ((HandlerMethod) handler).getMethod();
			Auth auth = m.getDeclaringClass().getAnnotation(Auth.class);
			if (auth != null) {
				auths = auth.value();
			}

			auth = m.getAnnotation(Auth.class);
			if (auth != null) {
				auths = auth.value();
			}

			if (auths != null) {
				UserEntity user = (UserEntity) request.getSession().getAttribute("user");
				if (user != null) {
					if (Arrays.binarySearch(auths, user.getUserRole().getCode()) < 0) {
						response.setStatus(HttpStatus.SC_FORBIDDEN);
						PrintWriter out = response.getWriter();
						out.write(JSONObject.toJSONString(RespJsonFactory.build(HttpStatus.SC_FORBIDDEN, "没有权限访问")));
						out.close();
						return false;
					}
				}
			}
		}
		return true;
	}
}
